<?php

namespace App\Kuafu\CustomerCoupon\Jobs;

use App\Kuafu\Customer\Service\CustomerPlatformService;
use App\Kuafu\CustomerCoupon\Model\SendCustomerCouponFailLog;
use App\Kuafu\CustomerCoupon\Service\CustomerCouponService;
use App\Kuafu\Wechat\Service\WechatCallbackService;
use App\Kuafu\Wechat\Service\WechatSendMessageService;
use App\Library\FeiShu\SendFs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class CustomerCouponArrivalNotice implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    //任务名称-发放优惠券到账提醒
    const  QUEUE_NAME = '{RMS-SEND-COUPON-ARRIVAL-NOTICE}';

    private $tries = 40;
    private $userId;
    private $couponName;
    private $startAt;
    private $endAt;
    private $remark;
    private $shopId;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($userId, $couponName, $startAt, $endAt, $remark, $shopId)
    {
        $this->userId     = $userId;
        $this->couponName = $couponName;
        $this->startAt    = $startAt;
        $this->endAt      = $endAt;
        $this->remark     = $remark;
        $this->shopId     = $shopId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //日志
        Log::channel('wechat')->info('发放优惠券到账提醒进入队列：', ['userId' => $this->userId, 'couponName' => $this->couponName]);
        // 每次间隔5s，最大延迟≈3分钟
        if ($this->attempts() >= $this->tries) {
            Log::channel('wechat')->info("发放优惠券到账提醒进入队列:用户id：{$this->userId}----优惠券名称：{$this->couponName}");
            return;
        }
        //查询用户openId
        $platformId = 1;
        $userOpenId = CustomerPlatformService::getUserFieldByUserId($this->userId, $platformId, ['openid']);
        if ($userOpenId) {
            WechatSendMessageService::couponArrivalNoticeSendMessage($this->couponName, $this->startAt, $this->endAt,
                $this->remark, $userOpenId->openid, $this->shopId);
        }
    }
}
